﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Security.Cryptography;
using System.Collections.Specialized;
using System.IO;
using System.Data.SqlClient;
using System.Net;

using Gateway01;

public partial class OnlinePay_Alipay_Receive : PageBase
{
    public string UserOfficeOK = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        bool OnlinePay_Alipay_Status_ON = PublicFunction.GetOptionsAsBoolean("OnlinePay_Alipay_Status_ON", false);

        if (!OnlinePay_Alipay_Status_ON)
        {
            PublicFunction.WriteLogini("未启用！");

            Response.Write("fail");     //返回给支付宝消息，失败

            return;
        }

        try
        {
            //***************************************************************     
            string key = PublicFunction.GetOptionsAsString("OnlinePay_Alipay_MD5Key", "");             //MD5-Key 
            string _input_charset = "utf-8";
            string partner = PublicFunction.GetOptionsAsString("OnlinePay_Alipay_UserNumber", "");  //卖家商户号

            //string alipayNotifyURL = "https://www.alipay.com/cooperate/gateway.do?";	        //支付接口
            //alipayNotifyURL = alipayNotifyURL + "service=notify_verify" + "&partner=" + partner + "&notify_id=" + Request.QueryString["notify_id"];
            string alipayNotifyURL = "http://notify.alipay.com/trade/notify_query.do?";
            alipayNotifyURL = alipayNotifyURL + "partner=" + partner + "&notify_id=" + Request.QueryString["notify_id"];

            //获取支付宝ATN返回结果，true是正确的订单信息，false 是无效的
            string responseTxt = Get_Http(alipayNotifyURL, 120000);
            int i;
            NameValueCollection coll;
            //Load QueryString variables into NameValueCollection variable.
            coll = Request.QueryString;

            // Get names of all QueryStrings into a string array.
            String[] requestarr = coll.AllKeys;

            //进行排序；
            string[] Sortedstr = AliPay.BubbleSort(requestarr);

            //构造待md5摘要字符串 ；

            StringBuilder prestr = new StringBuilder();

            for (i = 0; i < Sortedstr.Length; i++)
            {
                if (Request.QueryString[Sortedstr[i]] != "" && Sortedstr[i] != "sign" && Sortedstr[i] != "sign_type")
                {
                    if (i == Sortedstr.Length - 1)
                    {
                        prestr.Append(Sortedstr[i] + "=" + Request.QueryString[Sortedstr[i]]);
                    }
                    else
                    {
                        prestr.Append(Sortedstr[i] + "=" + Request.QueryString[Sortedstr[i]] + "&");

                    }
                }
            }

            prestr.Append(key);

            string mysign = AliPay.GetMD5(prestr.ToString(), _input_charset);
            string sign = Request.QueryString["sign"];
            string trade_status = Request.QueryString["trade_status"];
            string trade_no = Request.QueryString["trade_no"];              //支付宝交易号
            string out_trade_no = Request.QueryString["out_trade_no"];      //自己交易号
            string payment_type = Request.QueryString["payment_type"];      //支付类型
            string subject = Request.QueryString["subject"];                //商品名称，用户存放用户ID
            string subject_UnEncrypt = ShoveEL._Security.Encrypt.UnEncryptString(PublicFunction.GetCallCert(), subject);
            double total_fee = double.Parse(Request.QueryString["total_fee"].ToString());       //支付金额
            string seller_email = Request.QueryString["seller_email"];      //卖家账号

            if (seller_email != PublicFunction.GetOptionsAsString("OnlinePay_Alipay_UserName",""))
            {
                PublicFunction.GoError(ErrorNumber.NoData, "返回信息校验失败", this.GetType().BaseType.FullName);

                return;
            }

            if (mysign == sign && responseTxt == "true" && trade_status == "TRADE_FINISHED")   //验证支付发过来的消息，签名是否正确
            {
                User user;

                if (_User == null)
                {
                    user = new User();

                    user.ID = ShoveEL._Convert.StrToLong(subject_UnEncrypt, -1);

                    string Return = "";

                    if (user.GetUserInfoByID(ref Return) < 0)
                    {
                        PublicFunction.GoError(ErrorNumber.Unknow, "异常用户数据", this.GetType().BaseType.FullName);

                        return;
                    }

                    _User = user;
                }

                if (_User == null)
                {
                    PublicFunction.GoError(ErrorNumber.Unknow, "异常用户数据", this.GetType().BaseType.FullName);

                    return;
                }

                string ReturnDescription = "";
                _User.LoginDirect(ref ReturnDescription);

                if ((UserOfficeOK == null) && (UserOfficeOK == ""))
                {
                    this.Session["ZX_HTSW_1.0_User_Office"] = "UserOfficeOK";
                }

                if (WriteUserAccount(_User, out_trade_no.ToString(), total_fee.ToString(), "系统交易号：" + out_trade_no.ToString() + ",支付宝交易号：" + trade_no.ToString()))
                {
                    this.Response.Write("<script language='javascript'>window.top.location.href='http://" + PublicFunction.GetUrl() + "/BalanceCenter/Default.aspx?SubPage=../OnlinePay/OK.aspx'</script>");

                    return;
                }
                else
                {
                    PublicFunction.WriteLogini("写入返回数据出错！");

                    this.Response.Write("<script language='javascript'>window.top.location.href='http://" + PublicFunction.GetUrl() + "/BalanceCenter/Default.aspx?SubPage=../OnlinePay/Fail.aspx'</script>");

                    return;
                }
            }
            else
            {
                PublicFunction.WriteLogini("系统交易号：" + out_trade_no + " 支付宝交易号：" + trade_no + " 校验出错！responseTxt系统要求参数为true/false，实际返回：" + responseTxt.ToString() + " trade_status系统要求返回TRADE_FINISHED，实际返回： " + trade_status.ToString() + " 生成校验码：" + mysign.ToString() + "返回校验码：" + sign.ToString());
                this.Response.Write("<script language='javascript'>window.top.location.href='http://" + PublicFunction.GetUrl() + "/BalanceCenter/Default.aspx?SubPage=../OnlinePay/Fail.aspx'</script>");

                return;
            }
        }
        catch (Exception ex)
        {
            PublicFunction.WriteException(ex.Message);
            this.Response.Write("<script language='javascript'>window.top.location.href='http://" + PublicFunction.GetUrl() + "/BalanceCenter/Default.aspx?SubPage=../OnlinePay/Fail.aspx'</script>");

            return;
        }
    }

    #region Web 窗体设计器生成的代码

    override protected void OnInit(EventArgs e)
    {
        base.OnInit(e);
    }

    #endregion


    private bool WriteUserAccount(User _User, string orderid, string amount, string Memo)
    {
        double Money = ShoveEL._Convert.StrToDouble(amount, 0);
        if (Money == 0)
        {
            return false;
        }

        double FormalitiesFeesScale = PublicFunction.GetOptionsAsDouble("OnlinePay_Alipay_PayFormalitiesFeesScale", 0) / 100;
        double FormalitiesFees = Money - Math.Round(Money / (FormalitiesFeesScale + 1), 2);
        Money -= FormalitiesFees;

        int Return = 0;
        string ReturnDescription = "";

        bool ok = (_User.AddBalance(Money, FormalitiesFees, orderid, "支付宝支付", Memo, ref Return, ref ReturnDescription) == 0);

        if (!ok)
        {
            DataTable dt = DAL.Tables.T_UserPayDetails.Select("Result", "[id] = " + ShoveEL._Convert.StrToLong(orderid, 0).ToString(), "");

            if (dt == null || dt.Rows.Count == 0)
            {
                PublicFunction.WriteLogini("返回的交易号找不到对应的数据");

                return false;
            }

            int IsOK = ShoveEL._Convert.StrToInt(dt.Rows[0][0].ToString(), 0);

            if (IsOK == 1)
            {
                return true;
            }
            else
            {
                PublicFunction.WriteLogini("对应的数据未处理");

                return false;
            }
        }

        return ok;
    }

    //获取远程服务器ATN结果
    public String Get_Http(String a_strUrl, int timeout)
    {
        string strResult;
        try
        {
            HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(a_strUrl);
            myReq.Timeout = timeout;
            HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
            Stream myStream = HttpWResp.GetResponseStream();
            StreamReader sr = new StreamReader(myStream, Encoding.Default);
            StringBuilder strBuilder = new StringBuilder();
            while (-1 != sr.Peek())
            {
                strBuilder.Append(sr.ReadLine());
            }

            strResult = strBuilder.ToString();
        }
        catch (Exception exp)
        {

            strResult = "错误：" + exp.Message;
        }

        return strResult;
    }
}